package com.hontech.bread.app

import android.Manifest
import android.os.Build
import com.hontech.bread.R
import com.hontech.bread.api.keepTask
import com.hontech.bread.api.startUploadStatus
import com.hontech.bread.api.uploadOrder
import com.hontech.bread.device.Conn
import com.hontech.bread.device.mdb.Bill
import com.hontech.bread.device.mdb.Coin
import com.hontech.bread.device.mdb.Pos
import com.hontech.bread.store.Store
import com.hontech.bread.ui.dialog.ProgDialog
import com.hontech.bread.ui.dialog.runProg
import com.hontech.bread.utils.execIgnore
import com.hontech.bread.utils.grantPermission
import com.hontech.bread.utils.runOnUi
import com.hontech.bread.utils.stringById
import kotlinx.coroutines.delay


private var initFlag = false

private val initCbs = arrayListOf<suspend () -> Unit>()

fun globalInit() {
    if (initFlag) {
        return
    }
    initFlag = true
    runOnUi {
        var dialog: ProgDialog? = null
        runProg(stringById(R.string.t1733460848_19), stringById(R.string.t1733460848_20)) {
            dialog = it
            it.setMsg(stringById(R.string.t1733460848_21))
            Conn.autoOpen()

            it.setMsg(stringById(R.string.t1733460848_22))

            grantPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            grantPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            grantPermission(Manifest.permission.SEND_SMS)
            grantPermission(Manifest.permission.RECEIVE_SMS)
            grantPermission(Manifest.permission.READ_SMS)
            grantPermission(Manifest.permission.READ_PHONE_STATE)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                grantPermission(Manifest.permission.READ_PHONE_NUMBERS)
            }

            it.setMsg(stringById(R.string.t1733460848_23))
            Store.init()
            keepTask()
            startUploadStatus()

            execIgnore {
                it.setMsg(stringById(R.string.t1733460848_24))
                Coin.reset(false)
            }

            execIgnore {
                it.setMsg(stringById(R.string.t1733460848_25))
                Bill.reset(false)
            }

            execIgnore {
                it.setMsg("${stringById(R.string.t1733460848_26)}POS")
                Pos.reset(false)
            }

            it.setMsg(stringById(R.string.t1733460848_27))
            execIgnore { uploadOrder() }

            dialog = null
        }
        for (cb in initCbs) {
            cb()
        }
        initCbs.clear()
        if (dialog != null) {
            delay(10 * 1000)
            dialog?.dismiss()
        }
    }
}

suspend fun runWithInit(cb: suspend () -> Unit) {
    if (initFlag) {
        cb()
    } else {
        initCbs.add(cb)
    }
}



























